﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MoneyWentWhere.DataModel
{
    public static class ExtensionMethods
    {
        public static void AddOrReplace<K, V>(this Dictionary<K, V> dict, K key, V value)
        {
            if (dict.ContainsKey(key))
            {
                dict.Remove(key);
            }
            dict.Add(key, value);
        }

        public static V GetOrDefault<K, V>(this Dictionary<K, V> dict, K key, V defaultValue)
        {
            V value;
            if (dict.TryGetValue(key, out value)) { return value; }
            return defaultValue;
        }

        public static String RemovePrefix(this String s, params string[] prefixes)
        {
            foreach (String prefix in prefixes)
            {
                if (s.StartsWith(prefix))
                {
                    return s.Substring(prefix.Length);
                }
            }
            return s;
        }

        public static bool HasPrefix(this String s, params String[] prefixes)
        {
            foreach (String prefix in prefixes)
            {
                if (s.StartsWith(prefix))
                {
                    return true;
                }
            }
            return false;
        }

        public static String ToCsvEscapedString(this object o)
        {
            String cell = (o ?? "").ToString();
            cell = cell.Replace("\"", "\"\""); // Double quotes
            if (cell.Contains(",") || cell.Contains("\n")) { cell = "\"" + cell + "\""; }
            return cell;
        }

    }
}
